import axios from 'axios';
import { WeightRecord, KLineData, IndicatorData, ApiResponse, KLineQuery, TimeshareData } from '../types';

// 创建axios实例
const api = axios.create({
  baseURL: process.env.REACT_APP_API_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    console.log(`API请求: ${config.method?.toUpperCase()} ${config.url}`);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    console.error('API错误:', error.response?.data || error.message);
    return Promise.reject(error.response?.data || { error: error.message });
  }
);

export class WeightAPI {
  // 添加体重记录
  static async addWeight(record: Omit<WeightRecord, 'id' | 'created_at' | 'updated_at'>): Promise<ApiResponse> {
    return api.post('/weights', record);
  }

  // 获取体重记录
  static async getWeights(startDate?: string, endDate?: string): Promise<ApiResponse<WeightRecord[]>> {
    const params: any = {};
    if (startDate) params.start_date = startDate;
    if (endDate) params.end_date = endDate;
    
    return api.get('/weights', { params });
  }

  // 获取最新体重
  static async getLatestWeight(): Promise<ApiResponse<WeightRecord>> {
    return api.get('/weights/latest');
  }

  // 获取K线数据
  static async getKLineData(query: KLineQuery): Promise<ApiResponse<{period: string, kline: KLineData[]}>> {
    return api.get('/kline', { params: query });
  }

  // 获取分时图数据
  static async getTimeshareData(date?: string): Promise<ApiResponse<TimeshareData>> {
    const params = date ? { date } : {};
    return api.get('/timeshare', { params });
  }

  // 获取指标数据
  static async getIndicators(days?: number): Promise<ApiResponse<IndicatorData[]>> {
    const params = days ? { days } : {};
    return api.get('/indicators', { params });
  }

  // 删除体重记录
  static async deleteWeight(id: number): Promise<ApiResponse> {
    return api.delete(`/weights/${id}`);
  }

  // 更新体重记录
  static async updateWeight(id: number, record: Partial<WeightRecord>): Promise<ApiResponse> {
    return api.put(`/weights/${id}`, record);
  }

  // 生成模拟数据
  static async generateMockData(days: number = 30, startWeight: number = 95.5): Promise<ApiResponse> {
    return api.post('/mock-data', { days, start_weight: startWeight });
  }

  // 健康检查
  static async healthCheck(): Promise<any> {
    return axios.get('/health');
  }
}

export default api;
